<template>
  <div>
    <el-dialog :title="!formData.id?'添加部门':'编辑部门'" :visible="value" width="40%" @close="$emit('input',false)">
      <el-form ref="addForm" :model="formData" :rules="rules" label-width="120px">
        <el-form-item prop="name" label="部门名称">
          <el-input v-model="formData.name" placeholder="2-10个字符" style="width: 80%" size="mini" />
        </el-form-item>

        <el-form-item prop="code" label="部门编码">
          <el-input v-model="formData.code" placeholder="2-10个字符" style="width: 80%" size="mini" />
        </el-form-item>

        <el-form-item prop="managerId" label="部门负责人">
          <el-select v-model="formData.managerId" placeholder="请选择负责人" style="width: 80%" size="mini">
            <el-option v-for="item in managerList" :key="item.id" :label="item.username" :value="item.id" />
          </el-select>
        </el-form-item>

        <el-form-item prop="introduce" label="部门介绍">
          <el-input v-model="formData.introduce" placeholder="1-100个字符" type="textarea" size="mini" :rows="4" style="width: 80%" />
        </el-form-item>

        <el-form-item>
          <!-- 按钮 -->
          <el-row type="flex" justify="center">
            <el-col :span="12">
              <el-button size="mini" type="primary" @click="onSubmit">确定</el-button>

              <el-button size="mini" @click="$emit('input',false)">取消</el-button>

            </el-col>

          </el-row>

        </el-form-item>

      </el-form>

    </el-dialog>
  </div>
</template>
<!-- 1.定义一个formData的对象数据 -->
<!-- 2.定义一个rules的校验规则 -->
<!-- 3.在form中使用rules绑定rules -->
<!-- 4.在表单中使用model绑定formData -->
<!-- 5.在form中使用ref获取事件对象 -->
<!-- 6.在form-item中使用prop -->
<!-- 7.退出时清空表单以及确定时再次校验表单 -->
<script>
import { getDepartmentsAPI, getDepartmentDetailAPI,
  addDepartmentAPI, getManagerListAPI, updateDepartDataAPI } from '@/api/department'
import { Message } from 'element-ui'

export default {
  name: 'AddDep',
  props: {
    value: Boolean,
    currentNodeId: {
      type: Number,
      default: null
    }
  },
  data() {
    return {
      managerList: [],
      formData: {
        code: '',
        introduce: '',
        managerId: '',
        name: '',
        pid: ''
      },
      rules: {
        code: [
          { required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门编码的长度为2-10个字符', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 自定义校验规则
              let depList = await getDepartmentsAPI()
              // 判断是否是编辑模式
              if (this.formData.id) {
                // 编辑场景
                depList = depList.filter(item => item.id !== this.formData.id)
              }
              // result数组中是否存在 value值
              if (depList.some(item => item.code === value)) {
                callback(new Error('部门中已经有该编码了'))
              } else {
                callback()
              }
            }
          }
        ], // 部门编码
        introduce: [
          { required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { min: 1, max: 100, message: '部门介绍的长度为1-100个字符', trigger: 'blur' }
        ], // 部门介绍
        managerId: [
          { required: true, message: '部门负责人不能为空', trigger: 'blur' },
          {
            validator: async(rule, value, callback) => {
              // 自定义校验规则
              const depList = await getDepartmentsAPI()
              const managerList = depList.map(item => item.managerId)
              if (managerList.includes(value)) {
                callback()
              } else {
                callback(new Error('部门负责人不存在'))
              }
            }
          }
        ], // 部门负责人id
        name: [
          { required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 2, max: 10, message: '部门名称的长度为2-10个字符', trigger: 'blur' },
          {
            // 自定义校验模式
            validator: async(rule, value, callback) => {
              // value就是输入的名称
              let depList = await getDepartmentsAPI()
              if (this.formData.id) {
                // 编辑场景 排除自身
                depList = depList.filter(item => item.id !== this.formData.id)
              }
              // result数组中是否存在 value值
              if (depList.some(item => item.name === value)) {
                callback(new Error('部门中已经有该名称了'))
              } else {
                callback()
              }
            }
          }
        ] // 部门名称
        // pid: '' // 父级部门的id 不需要做校验
      }
    }
  },
  // 监听弹出层是否关闭
  watch: {
    value(val) {
      if (!val) {
        // 关闭的时候清空表单
        this.$refs.addForm.resetFields()
        this.formData = {
          code: '',
          introduce: '',
          managerId: '',
          name: '',
          pid: ''
        }
      }
    }
  },
  created() {
    this.getManagerData()
  },
  methods: {
    async onSubmit() {
      // 表单校验
      await this.$refs.addForm.validate()
      !this.formData.id
        ? await addDepartmentAPI({ ...this.formData, pid: this.currentNodeId })
        : await updateDepartDataAPI(this.formData)
      // 发送添加部门请求
      // 通知父组件更新
      this.$emit('updateDepartment')
      // 提示消息
      Message.success(`新增部门成功`)
    },
    async getManagerData() {
      const res = await getManagerListAPI()
      this.managerList = res
    },
    // 获取组织的详情
    async getDepartmentDetail() {
      this.formData = await getDepartmentDetailAPI(this.currentNodeId)
    }
  }
}
</script>

<style lang="scss" scoped>

</style>
